package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"go.uber.org/zap"
	"golang.org/x/net/context"
	basic "learn-go/learn-go/basic"
	"learn-go/learn-go/middleware"
	"learn-go/learn-go/router"
	"net/http"
	"os"
	"os/signal"
	"time"
)

var lgLogger = basic.XCLogger{}

func main() {

}

func init() {
	initHttp()
	initHttpGin()
	//initMetricsHttp()
}
func initLearnwg() {
	//basic.
}
func initMetricsHttp() {
	http.Handle("/metrics", promhttp.Handler())
	http.ListenAndServe(":7777", nil)
}
func initHttpGin() {
	go func() {
		logger, _ := zap.NewProduction()
		defer logger.Sync() // 退出前刷新日志缓冲区

		r := gin.New()
		r.Use(
			gin.Recovery(),
			middleware.ZapLogger(logger))

		gin.DefaultWriter = zap.NewStdLog(logger).Writer()
		gin.DefaultErrorWriter = zap.NewStdLog(logger).Writer()

		httpRouter(r)
		r.Run(":8080")
	}()
}
func initHttp() {
	logger, _ := zap.NewProduction()
	defer logger.Sync() // 退出前刷新日志缓冲区

	r := gin.New()
	r.Use(
		gin.Recovery(),
		middleware.ZapLogger(logger))

	gin.DefaultWriter = zap.NewStdLog(logger).Writer()
	gin.DefaultErrorWriter = zap.NewStdLog(logger).Writer()

	httpRouter(r)
	//r.Run(":8080")

	srv := &http.Server{
		Addr:    ":8080",
		Handler: r,
	}

	// 在goroutine中启动服务器
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			lgLogger.ERROR(fmt.Sprintf("listen: %s", err))
		}
	}()

	// 等待中断信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit
	lgLogger.Info("Shutting down server...")

	// 设置5秒超时上下文
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 优雅关闭服务器
	if err := srv.Shutdown(ctx); err != nil {
		lgLogger.ERROR(fmt.Sprintf("Server forced to shutdown:", err))
	}

}

func httpRouter(r *gin.Engine) {
	r.GET("/", router.ApiIndex())
	r.GET("/mypprof", router.ApiPprof())
}
